<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;

use Encore\Admin\Grid;
use Encore\Admin\Form;
use App\Models\Cdkey;
use App\Models\CdkeyRef;


use App\Admin\Extra\Search\Html;
use \Illuminate\Support\Facades\Input;

use App\Models\Area;
use Redirect;

class CdkeyController extends Controller
{
    public function index()
    {
        $use_data['area_all'] = Area::areaSelectData(0);
        $use_data['area_online'] = Area::areaSelectData();
        
        return Admin::content(function (Content $content)use($use_data) {
            $content->header('game cdkey manager');
            $content->row(Html::append([
                Html::likeRedirect('title', 'cdkey title', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));	

			$grid = Admin::grid(Cdkey::class, function(Grid $grid) use($use_data){
                $grid->model()->where('deleted_at', 0);

                $grid->actions(function($actions)use(&$row){
                    $row = $actions->row;
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append(Html::button('EDIT', '/admin/cdkey/edit?id='.$actions->getKey(), 'btn-goto btn-xs'));
                    $actions->append(Html::button('DEL', '/admin/cdkey/api-save?_id='.$actions->getKey().'&deleted_at=1', 'btn-goto btn-danger btn-xs btn-clear'));
                });

			    // 第一列显示id字段，并将这一列设置为可排序列
			    $grid->patch_id('ID')->sortable();
                $grid->model()->orderBy('patch_id', 'DESC');
                $grid->title('title')->limit(20);
                
                $grid->area_list('area')->display(function($value)use($use_data){
                    $disp = '';
                    foreach($value as $a_id){
                        $disp .= $use_data['area_all'][$a_id].",";
                    }
                    return  $disp;
                });
                $grid->created_at('create time')->display(function($value){
                    if (is_numeric($value)) {
                        $value = date("Y-m-d H:i:s", $value);
                    }
                    return $value;
                });

                $grid->expired_at('expired time')->display(function($value){
                    $color = "green"; 
                    ($value <= now()) && $color = "gray";
                    $value_format = date("Y-m-d H:i:s", $value);
                    return "<span style=\"color:{$color}\">{$value_format}</span>";
                });
                $grid->cdkey_link('cdkey')->display(function($value){
                    return Html::button('cdkey view', '/admin/cdkey/code?patch_id='.$this->patch_id, 'btn-goto btn-xs');
                });
                // $grid->cdkey_generate('generate code')->display(function($value){
                //     return Html::button('generate', '/admin/cdkey/generate?patch_id='.$this->patch_id, 'confirm-ajax btn-xs');
                // });
			    $grid->filter(function ($filter) use($use_data) {

                    // 模糊查询 注意
			        //$filter->where(function($query){
                    //    //$aids = \App\Models\EMail::getAccountByName('', 'playerName');
                    //    //var_dump($aids);exit;
                    //    $query->where('title', 'like', 'T%');
                    //}, '邮件标题', 'title');

                    $filter->like('title', 'area title')->placeholder('');
                    //$filter->equal('area_list')->select($use_data['area_online']);
                    $filter->equal('expired_at')->placeholder('is send cdkey');

                    //$filter->disableIdFilter();
			    });

            });
        
            $content->row($grid->render());

        });
    }

    public function anyEdit(){
        $id = Input::get('id');

        $one = Cdkey::find($id) ?: new Cdkey;

        $data['one'] = $one;

        \Log::debug("cdkey edit",[Area::areaSelectData(), $one->area_list]);
        return Admin::content(function($content) use($data){
		    $content->header('邮件编辑');
            $grid = Admin::Form(Cdkey::class, function(Form $form)use($data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);

                $form->text('title', 'title')->default($one->title);
                $form->textarea('remark', 'remark')->default($one->remark);
                $form->multipleSelect('area_list', 'area')->options(Area::areaSelectData())->default($one->area_list);
                $form->text('used_times', 'used times')->default($one->used_times);
                $form->datetime('expired_at', 'expired time')->default(date('Y-m-d H:i:s',$one->expired_at ?: strtotime(" 365 days")));
                //$form->textarea('prop', 'attach')->default($one->prop);
                $form->html(\App\Admin\Extra\Form\TForm::mutilSelectItem('items', $one->items, 'attach', '/admin/mail/item-all'), 'attach');
                $form->hidden('_id', 'id')->default($one->patch_id);

                //$form->html('<script>$("form").on("submit", function(event){if(!$("form").serializeArray().title) return false})</script>', '');

                //$form->tools(function (Form\Tools $tools) {
                //    // 去掉返回按钮
                //    $tools->disableBackButton();
                //    // 去掉跳转列表按钮
                //    $tools->disableListButton();
                //    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                //    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
                //});
                
                //$form->submitted(function(){
                //    return false;
                //});
                $form->saved(function (Form $form) {
                    \Log::debug(json_encode(['data'=>'save click']));
                    admin_toastr('laravel-admin 提示','success');
                    return response('success');
                });

                $form->disablePjax();
                $form->setAction('/admin/cdkey/api-save/');

            });
            $content->row($grid);
        });

    }

    public function anyAdd()
    {
        return $this->anyEdit();
    }

    public function anyApiSave(){
        $data = Input::all();

        $url = url()->to("/admin/cdkey");
        
        $one = Cdkey::find($data['_id']) ? : new Cdkey();

        Cdkey::assignByOut($one, $data);
        \Log::debug(json_encode(['data'=>$one, 'url' =>$url]));
        if (!$one->area_list || empty($one->items)) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('Cdkey save area or product items is empty!','error'), 'data' => $data]);
            return;
        }
        $one->save();
        
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('Cdkey save!','success'), 'data' =>$one->delete_at]);
        return;
    }

    public function anyGenerate()
    {
        $cdkey = Cdkey::find(\Request::get('patch_id'));
        $ret = Cdkey::GenerateCode($cdkey);
        \Log::info("cdkey generate code", [$ret, $cdkey]);
        if ($ret == 0){
            echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('Cdkey generate !','success'), 'data' =>$one->cdkey]);
            return;
        }
        $msg = 'Cdkey generate error!';
        if ($ret == -201){
            $msg = 'Not enough code lefted!';
        }
        echo json_encode(['code' => $ret, 'msg' => admin_toastr($msg, 'error'), 'data' => $data]);
    }

    public function anyCode()
    {
        $cdkey_obj = Cdkey::find(\Request::get('patch_id'));
        $use_data['area_all'] = Area::areaSelectData(0);
        $use_data['area_online'] = Area::areaSelectData();
        $use_data['cdkey'] = $cdkey_obj;
        
        return Admin::content(function (Content $content)use($use_data) {
            $content->header('cdkey:'.$use_data['cdkey']->title.'.');
            $content->row(Html::append([
                Html::likeRedirect('title', 'cdkey title', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));	

			$grid = Admin::grid(CdkeyRef::class, function(Grid $grid) use($use_data){
                $grid->model()->where('deleted_at', 0);

                $grid->actions(function($actions)use(&$row){
                    $row = $actions->row;
                    $actions->disableEdit();
                    $actions->disableDelete();
                    //$actions->append(Html::button('EDIT', '/admin/cdkey/edit?id='.$actions->getKey(), 'btn-goto btn-xs'));
                });

			    // 第一列显示id字段，并将这一列设置为可排序列
			    $grid->id('ID')->sortable();
                //$grid->model()->orderBy('patch_id', 'DESC');
                $grid->cdkey('cdkey');
                $grid->account('bind account')->display(function($value){
                    return $value;
                });
                $grid->player_id('bind player')->display(function($value){
                    return $value;
                });
                $grid->status('status')->display(function($value){
                    $label = CdkeyRef::$status_arr[$value];
                    return "<span>{$label}</span>";
                });

                $grid->updated_at('updated time');

			    $grid->filter(function ($filter) use($use_data) {

                    // 模糊查询 注意
			        //$filter->where(function($query){
                    //    //$aids = \App\Models\EMail::getAccountByName('', 'playerName');
                    //    //var_dump($aids);exit;
                    //    $query->where('title', 'like', 'T%');
                    //}, '邮件标题', 'title');

                    $filter->like('title', 'area title')->placeholder('');
                    //$filter->equal('area_list')->select($use_data['area_online']);
                    $filter->equal('expired_at')->placeholder('is send cdkey');

                    //$filter->disableIdFilter();
                });
                
                $excel = new \App\Admin\Extensions\CustomExporter("cdkey.".time(), CdkeyRef::getCustomExportHead(), null);
                $excel->setResouceFunc( function() {
                    return CdkeyRef::getCustomExportData();
                } );
                
                $grid->exporter($excel);
            });
        
            $content->row($grid->render());

        });
    }
}